package net.sos.translator;

import java.util.Locale;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

/**
 * The implementation class which makes use of the Google translation
 * API to do the translation.
 * 
 * @author SANJAY
 *
 */
public class GoogleTranslatorImpl implements ILocaleTranslator {

   private Locale fromLocale;
   
   private Locale toLocale;
      
   public GoogleTranslatorImpl() {
      super();   
   }

   public GoogleTranslatorImpl(Locale fromLocale, Locale toLocale) {
      super();
      this.fromLocale = fromLocale;
      this.toLocale = toLocale;
   }

   /* (non-Javadoc)
    * @see net.sos.translator.ILocaleTranslator#getFromLocale()
    */
   @Override
   public Locale getFromLocale() {      
      return fromLocale;
   }

   /* (non-Javadoc)
    * @see net.sos.translator.ILocaleTranslator#getToLocale()
    */
   @Override
   public Locale getToLocale() {
      return toLocale;
   }

   /* (non-Javadoc)
    * @see net.sos.translator.ILocaleTranslator#setFromLocale(java.util.Locale)
    */
   @Override
   public void setFromLocale(Locale fromLocale) {
      this.fromLocale = fromLocale;
   }

   /* (non-Javadoc)
    * @see net.sos.translator.ILocaleTranslator#setToLocale(java.util.Locale)
    */
   @Override
   public void setToLocale(Locale toLocale) {
      this.toLocale = toLocale;
   }

   /* (non-Javadoc)
    * @see net.sos.translator.ITranslator#translate(java.lang.String)
    */
   @Override
   public String translate(String text) {
      try {
         Translate.setHttpReferrer("http://www.google.com/");
         String translated = Translate.execute(text, localeToLanguage(fromLocale), localeToLanguage(toLocale));
         return translated;
      } catch(Exception e) {
         throw new RuntimeException(e);        
      }
   }

   private Language localeToLanguage(Locale locale) {
      for(Language lang : Language.values()) {
         if(lang.toString().equals(locale.getLanguage())) {
            return lang;
         }
      }
      return Language.valueOf(locale.getLanguage());
   }
   
}
